using System.Reflection;
using Aluetjen.EmailService.Domain.Models;
using Aluetjen.EmailService.Infrastructure.Persistence.Mappings;
using FluentNHibernate.Automapping;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;

namespace Aluetjen.EmailService.Infrastructure.Persistence
{
    public class NHibernateHelper
    {
        private readonly string _connectionString;
        private ISessionFactory _sessionFactory;

        public ISessionFactory SessionFactory
        {
            get { return _sessionFactory ?? (_sessionFactory = CreateSessionFactory()); }
        }

        public NHibernateHelper(string connectionString)
        {
            _connectionString = connectionString;
        }

        private ISessionFactory CreateSessionFactory()
        {
            return Fluently.Configure()
                .Database(MsSqlConfiguration.MsSql2008.ConnectionString(_connectionString))
                .Mappings(
                    m =>
                        {
                            m.FluentMappings.AddFromAssemblyOf<NHibernateHelper>();

                            IAutomappingConfiguration cfg = new ModelAutomappingConfiguration();

                            m.AutoMappings.Add(AutoMap.AssemblyOf<Entity>(cfg).UseOverridesFromAssemblyOf<NHibernateHelper>());
                        })
                .BuildConfiguration().SetProperty("hbm2ddl.auto", "update")
                .BuildSessionFactory();
        }
    }
}